//! The main module and entrypoint
//!
//! Various facilities of the kernels are implemented as submodules. The most
//! important ones are:
//!
//! - [`trap`]: Handles all cases of switching from userspace to the kernel
//! - [`syscall`]: System call handling and implementation
//!
//! The operating system also starts in this module. Kernel code starts
//! executing from `entry.asm`, after which [`rust_main()`] is called to
//! initialize various pieces of functionality. (See its source code for
//! details.)
//!
//! We then call [`batch::run_next_app()`] and for the first time go to
//! userspace.

#![no_std]
#![no_main]
//#![feature(panic_info_message)]
#[macro_use]
mod console;
mod batch;
mod lang_items;
mod sbi;
mod sync;
pub mod syscall;
pub mod trap;

use core::arch::global_asm;

global_asm!(include_str!("entry.asm"));
global_asm!(include_str!("link_app.S")); //link_app.S文件是在 cargo build 的时候，由脚本 os/build.rs 控制生成的。

#[unsafe(no_mangle)]
pub fn rust_main() -> ! {
    clear_bss(); //清空BSS段，初始化0
    println!("[kernel] Hello, world!");
    //设置trap处理入口地址
    trap::init();
    //batch::init();
    batch::run_next_app();
}

fn clear_bss() {
    //声明两个外部函数符号 sbss 和 ebss,这两个符号实际上不是函数，而是链接器定义的标签，标记了 .bss 段的起始地址和结束地址
    unsafe extern "C" {
        fn sbss();
        fn ebss();
    }
    //遍历，使用 write_volatile 确保写操作不会被编译器优化掉
    (sbss as usize..ebss as usize).for_each(|a| unsafe { (a as *mut u8).write_volatile(0) });
}
